package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.MessageDto;
import com.authine.cloudpivot.ext.enums.personal.MessageTypeEnum;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.cloudpivot.ext.utils.system.OrgUtils;
import com.authine.cloudpivot.ext.utils.system.UserUtils;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.org.dto.domainmodel.UnitType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * 个人中心-消息通知
 */
@Path("MessageService")
@Slf4j
public class MessageService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    /**
     * 删除消息(逻辑删除)
     *
     * @param dto
     * @return
     */
    @Path("delMessage")
    @POST
    @Operation(summary = "消息通知-全部消息-删除(逻辑删除)/消息通知-首页弹框-删除(逻辑删除)", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BO> delMessage(@Parameter MessageDto dto) {
        log.info("------------------------ 消息通知-全部消息-删除(逻辑删除)/消息通知-首页弹框-删除(逻辑删除) delMessage Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "ID集合必填");
        }
        for (String id : dto.getIds()) {
            dto.setId(id);
            dto.setDeleted(true);
            dto.setRead(false);
            updateMessage(dto);
        }
        return SingleResponse.buildSuccess();
    }

    /**
     * 已读消息
     *
     * @param dto
     * @return
     */
    @Path("readMessage")
    @POST
    @Operation(summary = "消息通知-全部消息-已读", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BO> readMessage(@Parameter MessageDto dto) {
        log.info("------------------------ 消息通知-全部消息-已读 readMessage Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "ID集合必填");
        }
        for (String id : dto.getIds()) {
            dto.setId(id);
            dto.setRead(true);
            dto.setDeleted(false);
            updateMessage(dto);
        }
        return SingleResponse.buildSuccess();
    }

    /**
     * 发布通知
     *
     * @param dto
     * @return
     */
    @Path("publishMessage")
    @POST
    @Operation(summary = "消息通知-平台通知-发布通知/消息通知-首页弹框-发布通知/消息通知-留言消息-发布留言", tags = CUSTOM_SERVICE, description = "content、type必填;如果type为HOMEPOP,receivers必填")
    public SingleResponse publishMessage(@Parameter MessageDto dto) {
        log.info("------------------------ 消息通知-平台通知-发布通知/消息通知-首页弹框-发布通知/消息通知-留言消息-发布留言 publishMessage Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getContent())) {
            return SingleResponse.buildFailure("-1", "内容必填");
        }
        if (StringUtils.isBlank(dto.getType())) {
            return SingleResponse.buildFailure("-1", "类型必填");
        }
        if(dto.getType().equals(MessageTypeEnum.NOTICE.name())){
            dto.setReceiver("所有组织");
        }
        if(!CollectionUtils.isEmpty(dto.getReceivers())&&dto.getType().equals(MessageTypeEnum.HOMEPOP.name())){
            for (String receiverName : dto.getReceivers()) {
                dto.setReceiver(receiverName);
                saveMessage(dto);
            }
        }else{
            saveMessage(dto);
        }
        return SingleResponse.buildSuccess();
    }

    /**
     * 回复
     *
     * @param dto
     * @return
     */
    @Path("replyMessage")
    @POST
    @Operation(summary = "消息通知-留言消息-回复", tags = CUSTOM_SERVICE, description = "content、type必填")
    public SingleResponse replyMessage(@Parameter MessageDto dto) {
        log.info("------------------------ 消息通知-留言消息-回复 replyMessage Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getContent())) {
            return SingleResponse.buildFailure("-1", "内容必填");
        }
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "消息ID必填");
        }
        SelectorFormat senderSF = UserUtils.getCurrentUser().createSelectorFormat();
        Map<String, Object> messageReplyMap = new HashMap<>();
        messageReplyMap.put("deleted", false);
        messageReplyMap.put("message_id", dto.getId());
        messageReplyMap.put("reply_content", dto.getContent());
        messageReplyMap.put("reply_id", senderSF);
        messageReplyMap.put("reply_name", senderSF.getName());
        String tableName = getTableName(ModelConst.T_MESSAGE);
        String sql = "update "+tableName+" set number = (select num from (select number+1 as num from "+tableName+" where id='"+dto.getId()+"') a) where id='"+dto.getId()+"'";
        //消息表数量+1更新
        jdbcTemplate.update(sql, new HashMap<>());
        return BoServiceUtils.createBo(ModelConst.T_MESSAGE_REPLY, Collections.singletonList(messageReplyMap));
    }

    /**
     * 查看回复
     *
     * @param dto
     * @return
     */
    @Path("replyMessageList")
    @POST
    @Operation(summary = "消息通知-留言消息-查看回复", tags = CUSTOM_SERVICE, description = "id必填")
    public SingleResponse<BOList> replyMessageList(@Parameter MessageDto dto) {
        log.info("------------------------ 消息通知-留言消息-回复 replyMessageList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "消息ID必填");
        }
        List<Map<String, Object>> result =  JdbcTemplateUtils.builder(ModelConst.T_MESSAGE_REPLY).selectField("*").eq("message_id", dto.getId())
                .queryForList();
        //构建结果集
        BOList bolist = new BOList();
        bolist.setData(result);
        bolist.setTotal(result.size());
        bolist.setSchemaCode(ModelConst.T_MESSAGE_REPLY);
        return SingleResponse.of(bolist);
    }

    private SingleResponse<BO>  saveMessage(MessageDto dto){
        Map<String, Object> map = new HashMap<>();
//        map.put("del", false);
        map.put("read", false);
        map.put("read_name", "未读");
        map.put("type", dto.getType());
        map.put("content", dto.getContent());
        map.put("type_name", MessageTypeEnum.valueOf(dto.getType()).text);
        map.put("number", 0);
        SelectorFormat senderSF = OrgUtils.getOrgByUserId().createSelectorFormat();
        map.put("sender_id", senderSF);
        map.put("sender", senderSF.getName());
        if(null != dto.getReceiverId()){
            map.put("receiver_id", dto.getReceiverId());
            map.put("receiver", dto.getReceiverId().getName());
        }else{
            SelectorFormat receiverSF = OrgUtils.getOrgByUserId().createSelectorFormat();
            map.put("receiver_id", receiverSF);
            map.put("receiver", receiverSF.getName());
        }
        return BoServiceUtils.createBo(ModelConst.T_MESSAGE, Collections.singletonList(map));
    }

    /**
     * 创建系统事件消息
     *
     * @param contents
     * @return
     */
    @Path("createdSystemMessage")
    @POST
    @Operation(summary = "创建系统事件消息", tags = CUSTOM_SERVICE, description = "contents必填")
    public SingleResponse<BO> createdSystemMessage(@Parameter List<String> contents) {
        log.info("------------------------ 创建系统事件消息 createdSystemMessage Param：{}------------------------", JSONObject.toJSONString(contents));
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(contents)){
            return SingleResponse.buildFailure("-1", "内容必填");
        }
        for (String content : contents) {
            Map<String, Object> map = new HashMap();
            map.put("read", false);
            map.put("read_name", "未读");
            map.put("type", MessageTypeEnum.EVENT.name());
            map.put("type_name", MessageTypeEnum.EVENT.text);
            map.put("content", content);
            list.add(map);
        }
        SingleResponse<BO> response = BoServiceUtils.createBo(ModelConst.T_MESSAGE, list);
        return response;
    }
}
